package com.wx.mall.sys.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RequestHandlerUtil {
    @Autowired
    private RestTemplate restTemplate;

    private HttpServletRequest request;

    public RequestHandlerUtil() {
    }

    private RequestHandlerUtil(HttpServletRequest request) {
        this.request = request;
    }
    public RequestHandlerUtil init(HttpServletRequest request) {
        this.request = request;
        return this;
    }
//    public RequestHandlerUtil init(HttpServletRequest request) {
//        return new RequestHandlerUtil(request);
//    }

    /**
     * 使用网易Api获取IP对应省份城市
     *
     * @return
     */
    public String getRegion() {
        String ip = getIPAddress();
        return getRegionByIp(ip);
    }

    /**
     * 使用网易Api获取IP对应省份城市
     * @param ip
     * @return
     */
    public String getRegionByIp(String ip) {
        // 使用网易Api接口
        String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
        // 淘宝Api 不稳定
//        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip +"&lang='zh-CN'&ie=%'utf-8%22'";
        String cityName = "";
//        // 通过RestTemplateBuilder 创建RestTemplate对象
//        RestTemplate template = builder.build();
        // 通过RestTemplate发送请求
        String result = restTemplate.getForObject(url, String.class);

        // 用正则表达式 解析返回结果
        String regex = "localAddress=\\{.*}";

        Matcher matcher = Pattern.compile(regex).matcher(result);
        if (matcher.find()){
            // 获取地址信息
            String group = matcher.group();
            // 或地址JSON
            String s = group.split("=")[1];
            // 解析成JSON对象
            JSONObject object = JSON.parseObject(s);
            String province = object.getString("province");
            cityName = province;
            String city = object.getString("city");
            if (!city.equals(province)){
                cityName += city;
            }
        }
        return cityName;
    }

    /**
     * 获取用户请求真实IP地址
     *
     * @return
     */
    public String getIPAddress() {
        //X-Forwarded-For：Squid 服务代理
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //Proxy-Client-IP：apache 服务代理
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //X-Real-IP：nginx服务代理
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ip != null && ip.length() != 0) {
            ip = ip.split(",")[0];
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
            //根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ip = inet.getHostAddress();
        }

        return ip;
    }

    /**
     * 获取用户请求的浏览器
     *
     * @return
     */
    public String getBrowser() {
        String userAgent = request.getHeader("User-Agent").toLowerCase();
//        String os = getOperatingSystem();
        String s;
        String version;
        String msieP = "msie ([\\d.]+)";
        String firefoxP = "firefox\\/([\\d.]+)";
        String chromeP = "chrome\\/([\\d.]+)";
        String safariP = "version\\/([\\d.]+).*safari";

        // IE
        Pattern pattern = Pattern.compile(msieP);
        Matcher mat = pattern.matcher(userAgent);
        if (mat.find()) {
            //  MSIE 9.0
            s = mat.group();
            // 9.0
            String temp = s.split(" ")[1];
            // 9 注意转义 .
            version = temp.split("\\.")[0];

//            return "IE " + version + " - " + os;
            return "IE " + version;
        }
        // firefox
        mat = Pattern.compile(firefoxP).matcher(userAgent);
        if (mat.find()) {
            // firefox/74.0
            s = mat.group();
            // 74 注意转义 .
            version = s.split("/")[1].split("\\.")[0];

//            return "FireFox " + version + " - " + os;
            return "FireFox " + version;
        }
        // chrome
        mat = Pattern.compile(chromeP).matcher(userAgent);
        if (mat.find()) {
            // chrome/80.0.3987.149
            s = mat.group();
            // 80 注意转义 .
            version = s.split("/")[1].split("\\.")[0];

//            return "Chrome " + version + " - " + os;
            return "Chrome " + version;
        }
        // Safari
        mat = Pattern.compile(safariP).matcher(userAgent);
        if (mat.find()) {
            // Version/5.1 Safari
            s = mat.group();
            // 5 注意转义 .
            version = s.split("/")[1].split("\\.")[0];

//            return "Safari " + version + " - " + os;
            return "Safari " + version;
        }
        return "未知浏览器";
    }

    /**
     * 获取用户操作系统信息
     *
     * @return
     */
    public String getOperatingSystem() {
        String ua = request.getHeader("User-Agent");

        String userAgent = ua.toLowerCase();
        // 操作系统OS信息
        if (userAgent.indexOf("windows") >= 0) {
            return "Windows";
        } else if (userAgent.indexOf("mac") >= 0) {
            return "Mac";
        } else if (userAgent.indexOf("x11") >= 0) {
            return "Unix";
        } else if (userAgent.indexOf("android") >= 0) {
            return "Android";
        } else if (userAgent.indexOf("iphone") >= 0) {
            return "IPhone";
        } else {
            return "UnKnown, More-Info: " + ua;
        }
    }
}
